from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.models import AllowedIP, Order, User
from app.database.services.users import get_user


async def get_ip(session: AsyncSession, ip_id: int) -> AllowedIP:

    q = select(AllowedIP).where(AllowedIP.id == ip_id)

    res = await session.execute(q)

    return res.scalar()


async def add_allowed_ip(session: AsyncSession, user_id: int, ip_address: str) -> None:
    user = await get_user(session, user_id)

    allowed_ip = AllowedIP(ip_address=ip_address, user=user, user_id=user_id)
    session.add(allowed_ip)
    await session.commit()


async def add_ip_to_order(
    session: AsyncSession, order: Order, allowed_ip: AllowedIP
) -> None:
    order.allowed_ips.append(allowed_ip)

    await session.commit()


async def remove_ip_from_order(
    session: AsyncSession, order: Order, allowed_ip: AllowedIP
) -> None:
    order.allowed_ips.remove(allowed_ip)

    await session.commit()


async def get_allowed_ips(session: AsyncSession, user_id: int) -> list[AllowedIP]:

    q = select(AllowedIP).outerjoin(AllowedIP.user).filter(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def get_allowed_ip_by_order(
    session: AsyncSession, user_id: int, order_id: int
) -> AllowedIP:

    q = (
        select(AllowedIP)
        .join(AllowedIP.orders)
        .join(AllowedIP.user)
        .filter(Order.id == order_id)
        .filter(User.telegram_id == user_id)
    )

    res = await session.execute(q)

    return res.scalar()
